import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Header from './Header';
import Footer from './Footer';
import MainHeader from './MainHeader';
import MainBody from './MainBody';
import MainFooter from './MainFooter';
import localforage from 'localforage';
import SnowflakeWorker from 'snowflake-worker';

interface tabItemType {
    key: string;
    name: string;
}

interface todoItemType {
    id: string;
    title: string;
    completed: boolean;
    create_time: number;
    update_time: number;
    delete_time: number;
}

interface IState {
    currentTab: string;
    dataList: todoItemType[];
    tabsList: tabItemType[];
    totalCount: number;
    pendingCount: number;
    completedCount: number;
    allCompleted: boolean;
    isLoading: boolean;
}

class Layout extends Component<any, IState> {
    private snowflakeWorker: SnowflakeWorker;

    constructor(props: any) {
        super(props);
        // 获取路由参数
        const { pathname } = window.location;
        // 拆解tab名称
        const _tab = pathname.replace('/', '').replace('#', '');

        this.state = {
            currentTab: _tab || 'all', // 默认选中选项卡
            dataList: [],
            tabsList: [
                { key: 'all', name: '全部' },
                { key: 'pending', name: '待完成' },
                { key: 'completed', name: '已完成' },
            ],
            totalCount: 0,
            pendingCount: 0,
            completedCount: 0,
            allCompleted: false,
            isLoading: true,
        };

        this.snowflakeWorker = new SnowflakeWorker(1, 1);
        console.warn('Layout生命周期：constructor');
    }

    async componentDidMount() {
        try {
            // 加载本地存储数据
            await this.loadData();
        } catch (error) {
            console.error('数据加载错误：', error);
        } finally {
            this.setState({ isLoading: false });
        }
        console.warn('Layout生命周期：componentDidMount');
    }

    componentDidUpdate() {
        console.warn('Layout生命周期：componentDidUpdate');
    }

    componentWillUnmount() {
        console.warn('Layout生命周期：componentWillUnmount');
    }

    /**
     * 初始化载入数据
     */
    loadData = async () => {
        let _data: todoItemType[] = [];

        try {
            await localforage.iterate((obj: any, key, iterationNumber) => {
                //if (obj && typeof obj === 'object' && 'id' in obj && 'title' in obj && 'completed' in obj && 'create_time' in obj) {
                if (obj && typeof obj === 'object') {
                    const itemAsItemType = obj as todoItemType;
                    _data.push(itemAsItemType);
                }
                console.log('第' + iterationNumber + '条数据获取完成。');
            });

            //_data.reverse();
            _data.sort((a, b) => b.create_time - a.create_time); // 降序排序
        } catch (err) {
            console.error(err);
            throw err;
        }

        this.setState({ dataList: _data });
        console.log('全部数据获取完成');
        //return _data;
    };

    /**
     * 获取数据方法
     * @param itemId
     */
    getTodoItem = async (itemId: string) => {
        await localforage.getItem(itemId).then((itemObj: todoItemType) => {
            console.log('11111查询{' + itemId + '}数据完成：', itemObj);
            if (itemObj) {
                return itemObj;
            }
        }).catch((err) => {
            console.error(err);
            return {};
        });
    };

    /**
     * 添加数据方法
     * @param value
     */
    addTodoItem = (value: string) => {
        const { currentTab } = this.state;
        const snowflakeId = this.snowflakeWorker.nextId();

        const itemObj = {
            id: snowflakeId,
            title: value,
            completed: false,
            create_time: Math.round(new Date().getTime() / 1000),
            update_time: 0,
            delete_time: 0,
        };

        this._updateDataState(itemObj);

        // 写入indexDB数据库。key为id，value为对象
        localforage.setItem(itemObj.id, itemObj).then((value) => {
            console.log(value);
        }).catch((err) => {
            console.error(err);
        });

        // 如果在已完成选项卡添加，就切换到待完成
        if (currentTab === 'completed') {
            this.switchTabHandle('pending');
        }
    };

    /**
     * 编辑数据方法
     * @param itemId
     * @param title
     */
    updateTodoItem = (itemId: string, title: string) => {
        console.info('before updateTodoItem', itemId, title);

        if (!title) {
            alert('标题不能为空');
            return;
        }

        localforage.getItem(itemId)
            .then((itemObj: todoItemType) => {
                console.log('查询{' + itemId + '}数据完成：', itemObj);

                itemObj.title = title;
                itemObj.update_time = Math.round(new Date().getTime() / 1000); // 更新时间

                localforage.setItem(itemId, itemObj)
                    .then(() => {
                        this._updateDataState(itemObj);
                        console.log('更新{' + itemId + '}数据完成.');
                    })
                    .catch((err) => {
                        console.log('更新{' + itemId + '}数据时发生错误：', err);
                    });
            })
            .catch((err) => {
                console.log('获取{' + itemId + '}数据时发生错误：', err);
            });
    };

    /**
     * 删除数据方法
     * @param itemId
     */
    deleteTodoItem = (itemId: string) => {
        console.info('before deleteTodoItem', itemId);
        const updatedDataList = this.state.dataList.filter(item => item.id!== itemId);
        localforage.removeItem(itemId).then(() => {
            this.setState({ dataList: updatedDataList });
            console.log('删除{' + itemId + '}数据完成.');
        }).catch((err) => {
            console.log('删除{' + itemId + '}数据时发生错误：', err);
        });
    };

    /**
     * 清除已完成数据方法
     */
    clearCompletedTodoItem = () => {
        console.info('before clearCompletedTodoItem');
        const _completedDataList = this.state.dataList.filter(item => item.completed);

        _completedDataList.forEach(item => {
            localforage.removeItem(item.id).then(() => {
                console.log(`删除${item.id}数据完成.`);

                // 更新列表数据状态
                this.setState({ dataList: this.state.dataList.filter(item =>!item.completed) });
            }).catch((err) => {
                console.error(`删除${item.id}数据时发生错误：`, err);
            });
        });
    };

    /**
     * 勾选数据方法
     * @param itemId
     */
    checkTodoItem = (itemId: string) => {
        console.info('before checkTodoItem', itemId);

        localforage.getItem(itemId)
            .then((itemObj: todoItemType) => {
                console.log('查询{' + itemId + '}数据完成：', itemObj);

                itemObj.completed = !itemObj.completed;

                localforage.setItem(itemId, itemObj)
                    .then(() => {
                        this._updateDataState(itemObj);
                        console.log('更新{' + itemId + '}数据完成.');
                    })
                    .catch((err) => {
                        console.log('更新{' + itemId + '}数据时发生错误：', err);
                    });
            })
            .catch((err) => {
                console.log('获取{' + itemId + '}数据时发生错误：', err);
            });
    };

    /**
     * 更新数据列表状态
     * @param itemObj
     */
    _updateDataState = (itemObj: todoItemType) => {
        const { dataList } = this.state;
        const index = dataList.findIndex(item => item.id === itemObj.id);

        if (index !== -1) {
            const updatedDataList = [...dataList];
            updatedDataList[index] = itemObj;
            this.setState({ dataList: updatedDataList }, () => console.log('状态更新完成'));
        } else {
            this.setState(prevState => ({
                dataList: [itemObj, ...prevState.dataList]
            }), () => console.log('状态更新完成'));
        }
    };

    /**
     * 全选数据列表状态
     * @param shouldCompleteAll
     */
    toggleAllTodos = (shouldCompleteAll: boolean) => {
        const newDataList = this.state.dataList.map(item => ({
            ...item,
            completed: shouldCompleteAll
        }));

        // 同步更新本地存储中的数据状态
        newDataList.forEach(item => {
            localforage.setItem(item.id, item).catch((err) => {
                console.error(`Error updating item ${item.id}:`, err);
            });
        });

        this.setState({ dataList: newDataList });
    };

    switchTabHandle = (tabKey: string) => {
        this.setState({
            currentTab: tabKey
        });

        // 更新计数器
        this.handleUpdateCounts();
    };

    // 处理 counts 更新的方法
    handleUpdateCounts = () => {
        const { currentTab, dataList } = this.state;
        const totalCount = dataList.length;
        const pendingCount = dataList.filter(item => !item.completed).length;
        const completedCount = dataList.filter(item => item.completed).length;

        let allCompleted = false;

        switch (currentTab) {
            case 'all':
                allCompleted = totalCount > 0 && totalCount === completedCount;
                break;
            case 'pending':
                allCompleted = false;
                break;
            case 'completed':
                allCompleted = completedCount > 0;
                break;
            default:
                break;
        }

        // 更新当前选项卡
        this.setState({
            allCompleted: allCompleted,
            totalCount: totalCount,
            pendingCount: pendingCount,
            completedCount: completedCount
        });
    };

    render() {
        const {
            currentTab,
            dataList,
            tabsList,
            totalCount,
            pendingCount,
            completedCount,
            allCompleted,
            isLoading
        } = this.state;

        const counts = {
            totalCount: totalCount,
            pendingCount: pendingCount,
            completedCount: completedCount
        };

        return (
            <Router>
                {<div className={`loading${isLoading? '' : ' hidden'}`}>
                    <div className="loading-icon"></div>
                    <span>正在加载中...</span>
                </div>}
                <Header />
                <main className="app-main">
                    <MainHeader
                        currentTab={currentTab}
                        addTodoItem={this.addTodoItem}
                        toggleAllTodos={this.toggleAllTodos}
                        allCompleted={allCompleted}
                        counts={counts}
                    />
                    <Routes>
                        <Route path="/" element={
                            <MainBody
                                currentTab={currentTab}
                                dataList={dataList}
                                /*getTodoItem={this.getTodoItem}*/
                                checkTodoItem={this.checkTodoItem}
                                updateTodoItem={this.updateTodoItem}
                                deleteTodoItem={this.deleteTodoItem}
                                handleUpdateCounts={this.handleUpdateCounts}
                            />
                        } />
                        <Route path="/:tab" element={
                            <MainBody
                                currentTab={currentTab}
                                dataList={dataList}
                                /*getTodoItem={this.getTodoItem}*/
                                checkTodoItem={this.checkTodoItem}
                                updateTodoItem={this.updateTodoItem}
                                deleteTodoItem={this.deleteTodoItem}
                                handleUpdateCounts={this.handleUpdateCounts}
                            />
                        } />
                    </Routes>
                    <MainFooter
                        currentTab={currentTab}
                        tabsList={tabsList}
                        switchTabHandle={this.switchTabHandle}
                        clearCompletedTodoItem={this.clearCompletedTodoItem}
                        counts={counts}
                    />
                </main>
                <Footer />
                <div className="bg_wrapper"></div>
            </Router>
        );
    }
}

export default Layout;